#ifndef ROPPENLISTENER_H_
#define ROPPENLISTENER_H_

#include <QtNetwork>
#include "../../include/dto/3d/matrix.h"

class CountAndSend : public QObject {
	Q_OBJECT
public:
	CountAndSend(QTcpSocket *_socket):QObject() {
		socket = _socket;
		s = new QString;
		time = TimeHelper::currentTimeMillis();
		
		QTimer *timer = new QTimer( this);
		connect( timer, SIGNAL(timeout()), this, SLOT(send()) );
		timer->start( 40 ); 
		counter = 0;
	}
	virtual ~CountAndSend() {}
	void write(const char *data) {
		s->append(data);
		send();
	}
	public slots:
	void send() {
		if (socket->state()== QAbstractSocket::ConnectedState) {
			if (time+40 < TimeHelper::currentTimeMillis()) {
				socket->write(s->toUtf8().data());
				s = new QString;
				time = TimeHelper::currentTimeMillis();
			}
		}
		
		else if (++counter>50){
			socket ->abort();
			socket->connectToHost("192.168.1.103",6667);
			counter = 0;
		}
	}
private:
	QString *s;
	unsigned long time;
	QTcpSocket *socket;
	int counter;
};

class NetIntListener : public Listener {
public:
	~NetIntListener() {}
	NetIntListener(int _objectSelect,CountAndSend *_socket) {
		socket = _socket;
		objectSelect=_objectSelect;
		acceptedValues = INT|FLOAT|TEXT;
	}
	short intChanged(long _id,unsigned int _index,Value<int> *c) {
		std::ostringstream os;
		os << objectSelect;
		int index = (int)_index;
		if (index<10) {
			os << '0';
		}
		os << index;
		os << c->getValue() << '\n';
//		printf(os.str().data());
//		printf(" : sent\n");
		socket->write(os.str().data());
		return true;
	}
	
	short floatChanged(long _id,unsigned int _index,Value<float> *c) {
			std::ostringstream os;
			os << objectSelect;
			int index = (int)_index;
			if (index<10) {
				os << '0';
			}
			os << index;
			os << c->getValue()<< '\n';
//			printf(os.str().data());
//			printf(" : sent\n");
			socket->write(os.str().data());
			return true;
		}
	short stringChanged(long _id,unsigned int _index,Value<std::string> *c) {
				std::ostringstream os;
				os << objectSelect;
				int index = (int)_index;
				if (index<10) {
					os << '0';
				}
				os << index;
				os << c->getValue()<< '\n';
//				printf(os.str().data());
//				printf(" : sent\n");
				socket->write(os.str().data());
				return true;
			}
	
private:
	int objectSelect;
	CountAndSend *socket;
	
};

#endif /*ROPPENLISTENER_H_*/
